#include "app_common.h"
#include <pthread.h>
#include <mqueue.h>

mqd_t mqd_id;
int priority = 1;
char buffer[1024];
ssize_t rxlen = 0;
void *first_thread_func(void *arg)
{
    while (1)
    {
        rxlen = mq_receive(mqd_id, buffer, sizeof(buffer), &priority);
        if (rxlen >= 0)
        {
            log_info("收到:%.*s", (int)rxlen, buffer);
        }
        else
        {
            log_error("mq_receive失败");
            break;
        }
    }
}

int main(int argc, char const *argv[])
{
    mq_unlink("/mqtest");
    struct mq_attr attr;
    attr.mq_flags = 0;      // 阻塞模式
    attr.mq_maxmsg = 10;    // 最大消息数
    attr.mq_msgsize = 1024; // 每条消息最大长度
    attr.mq_curmsgs = 0;
    // 创建消息队列
    mqd_id = mq_open("/mqtest", O_CREAT | O_RDWR, 0666, &attr);

    if (mqd_id == -1)
    {
        log_error("mqueue创建失败");
        return 1;
    }
    log_info("mqueue创建成功");

    pthread_t pt1;
    if (pthread_create(&pt1, NULL, first_thread_func, NULL) != 0)
    {
        log_error("线程创建失败");

        return 1;
    }
    log_info("线程创建成功");

    while (1)
    {
        mq_send(mqd_id, "hello", strlen("hello"), priority);
        sleep(2);
    }

    pthread_join(pt1, NULL);

    return 0;
}